package com.test25_常用类2;

/**
 * ThreadLocal，线程内部的存储类
 */
public class Demo04_ThreadLocal {

    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
        test4();
    }

    /**
     * 传统引用传递
     */
    public static void test1() {
        Message message = new Message();
        message.setContent("沐言科技：www.yootk.com");
        MessagePrint.print(message);
    }

    /**
     * 使用中间类
     */
    public static void test2() {
        Resource2.message = new Message();
        Resource2.message.setContent("沐言科技：www.yootk.com");
        MessagePrint2.print();  // 不再传递引用对象
    }

    /**
     * 多线程下的问题
     */
    public static void test3() {
        String[] values = new String[] {
                "沐言科技：www.yootk.com",
                "李兴华编程训练营：yootk.ke.qq.com",
                "人才培养大纲：edu.yootk.com"
        };
        for (String msg : values) {
            new Thread(() -> {
                Resource2.message = new Message();
                Resource2.message.setContent(msg);
                MessagePrint2.print();
            }).start();
        }
    }

    /**
     * 通过ThreadLocal解决多线程并发访问的问题
     */
    public static void test4() {
        String[] values = new String[] {
                "沐言科技：www.yootk.com",
                "李兴华编程训练营：yootk.ke.qq.com",
                "人才培养大纲：edu.yootk.com"
        };
        for (String msg : values) {
            new Thread(() -> {
                Resource3.MESSAGES.set(new Message());
                Resource3.MESSAGES.get().setContent(msg);
                MessagePrint3.print();
            }).start();
        }
    }
}

class Message {
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

/**
 * 传统引用传递
 */
class MessagePrint {
    public static void print(Message obj) {
        System.out.println("【MessagePrint】" + obj.getContent());
    }
}

/**
 * 使用中间类存放Message
 */
class MessagePrint2 {
    public static void print() {
        System.out.printf("【%s】%s%n", Thread.currentThread().getName(), Resource2.message.getContent());
    }
}

class Resource2 {    // 中间类
    public static Message message;
}

/**
 * 使用中间类存放ThreadLocal<Message>
 */
class MessagePrint3 {
    public static void print() {
        // 获取当前线程所保存的Message对象
        System.out.printf("【%s】%s%n", Thread.currentThread().getName(), Resource3.MESSAGES.get().getContent());
    }
}

class Resource3 {   // 中间类
    public static final ThreadLocal<Message> MESSAGES = new ThreadLocal<>();
}
